package cn.yhbk.web.modules.manager.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.yhbk.web.common.exception.ApiException;
import cn.yhbk.web.modules.manager.Mapper.ActivityExamineMapper;
import cn.yhbk.web.modules.manager.Mapper.ActivityMapper;
import cn.yhbk.web.modules.manager.Pojo.DTO.Activity.ActivityDetailDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.Activity.ActivityDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.Activity.ActivityGpa;
import cn.yhbk.web.modules.manager.Pojo.DTO.Activity.ActivityResp;
import cn.yhbk.web.modules.manager.Pojo.Entity.ActivityDetail;
import cn.yhbk.web.modules.manager.Pojo.Entity.ActivityEntity;
import cn.yhbk.web.modules.manager.Pojo.Entity.ActivityExamineEntity;
import cn.yhbk.web.modules.manager.Pojo.VO.Activity.*;
import cn.yhbk.web.modules.manager.Service.ActivityService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, ActivityEntity> implements ActivityService {

    @Autowired
    private ActivityExamineMapper activityExamineMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ActivityResp getActivityList() {
        String activityStr = redisTemplate.opsForValue().get("activityList");
        if (activityStr != null){
            return JSONUtil.toBean(activityStr, ActivityResp.class);
        }
        ActivityResp activityResp = new ActivityResp();
        // 查询所有活动
        List<ActivityDto> activityList = this.baseMapper.selectList(new LambdaQueryWrapper<ActivityEntity>()
                                        .eq(ActivityEntity::getStatus, 1))
                                        .stream()
                                        .map(item -> BeanUtil.copyProperties(item, ActivityDto.class))
                                        .collect(Collectors.toList());
        // 查询所有A类加分
        List<ActivityDetailDto> aList = this.baseMapper.selectAList()
                .stream()
                .map(item -> BeanUtil.copyProperties(item, ActivityDetailDto.class))
                .collect(Collectors.toList());
        // 查询所有b类加分
        List<ActivityDetailDto> bList = this.baseMapper.selectBList()
                .stream()
                .map(item -> BeanUtil.copyProperties(item, ActivityDetailDto.class))
                .collect(Collectors.toList());

        // 查询除活动外的加分绩点
        List<ActivityGpa> gpaList = this.baseMapper.selectGpaList();

        activityResp.setActivityGpaList(gpaList);
        activityResp.setActivityList(activityList);
        activityResp.setBDetailList(bList);
        activityResp.setADetailList(aList);

        redisTemplate.opsForValue().set("activityList", JSONUtil.toJsonStr(activityResp), 5, TimeUnit.HOURS);
        return activityResp;
    }

    @Override
    public Boolean submit(ActivityVo activityVo, Long stuId) {
        ActivityExamineEntity activityExamineEntity = BeanUtil.copyProperties(activityVo, ActivityExamineEntity.class);
        activityExamineEntity.setExamineStatus(0);
        activityExamineEntity.setStuId(stuId);
        activityExamineEntity.setIsExamine(0);
        activityExamineEntity.setProve(JSONUtil.toJsonStr(activityVo.getImageList()));

        activityExamineMapper.insert(activityExamineEntity);
        return true;
    }

    @Transactional
    @Override
    public Boolean examine(Long adminId, Long activityExamineId, Integer examineStatus) {
        // 更新审核表
        ActivityExamineEntity activityExamineEntity = activityExamineMapper.selectById(activityExamineId);
        if (activityExamineEntity.getIsExamine() == 1){
            throw new ApiException("活动已审核过了");
        }

        activityExamineEntity.setExamineStatus(examineStatus);
        activityExamineEntity.setAdminId(adminId);
        activityExamineEntity.setIsExamine(1);
        activityExamineMapper.updateById(activityExamineEntity);

        // 同意
        if (examineStatus == 1){
            // 插入活动表
            ActivityEntity activityEntity = BeanUtil.copyProperties(activityExamineEntity, ActivityEntity.class);
            activityEntity.setStatus(1);
            this.baseMapper.insert(activityEntity);

            if (activityEntity.getCategoryId().equals(2L)){
//                // 比赛
//                ActivityDetail activityDetail = BeanUtil.copyProperties(activityExamineEntity, ActivityDetail.class);
//                // 插入详情表
//                if (activityExamineEntity.getCategory().equals("A")){
//                    this.baseMapper.insertADetail(activityDetail);
//                } else {
//                    this.baseMapper.insertBDetail(activityDetail);
//                }
            } else {
                // 其他活动
                ActivityGpa activityGpa = BeanUtil.copyProperties(activityExamineEntity, ActivityGpa.class);
                activityGpa.setId(activityEntity.getContestNo());

                this.baseMapper.insertGpa(activityGpa);
            }

            // 删除redis中的缓存
            redisTemplate.delete("activityList");
        }

        return true;
    }

    @Override
    @Transactional
    public Boolean adminUpdate(ActivityUpdate activityUpdate) {
        ActivityEntity activityEntity = this.baseMapper.selectById(activityUpdate.getContestNo());
        BeanUtils.copyProperties(activityUpdate, activityEntity);
        this.baseMapper.updateById(activityEntity);
        // 删除redis中的缓存
        redisTemplate.delete("activityList");

//        // 保存加分绩点
//        if (activityUpdate.getCategoryId().equals(2L)){
//            // 比赛
////            if (activityUpdate.getCategory().equals("A")){
////                int count = this.baseMapper.queryADetailIsExit(activityUpdate.getGrade(),
////                        activityUpdate.getLevel(), activityUpdate.getGpa());
////                if (count == 0){
////                    // 不存在，就保存
////                    this.baseMapper.insertADetail(new ActivityDetail(activityUpdate.getGrade(), activityUpdate.getLevel(),
////                            activityUpdate.getGpa()));
////                }
////            } else if (activityUpdate.getCategory().equals("B")) {
////                int count = this.baseMapper.queryBDetailIsExit(activityUpdate.getGrade(),
////                        activityUpdate.getLevel(), activityUpdate.getGpa());
////                if (count == 0){
////                    // 不存在，就保存
////                    this.baseMapper.insertBDetail();
////                }
////            }
//
//        } else {
//            // 其他活动
//            ActivityGpa activityGpa = BeanUtil.copyProperties(activityUpdate, ActivityGpa.class);
//            activityGpa.setId(activityEntity.getContestNo());
//            this.baseMapper.updateGpaByContestNo(activityGpa);
//        }
        return true;
    }


    @Override
    public void insert(ActivityVo activityVo) {
        // 插入活动表
        ActivityEntity activityEntity = BeanUtil.copyProperties(activityVo, ActivityEntity.class);
        activityEntity.setStatus(1);
        this.baseMapper.insert(activityEntity);

        if (activityEntity.getCategoryId().equals(2L)){
//            // 比赛
//            ActivityDetail activityDetail = BeanUtil.copyProperties(activityVo, ActivityDetail.class);
//            // 插入详情表
//            if (activityVo.getCategory().equals("A")){
//                this.baseMapper.insertADetail(activityDetail);
//            } else {
//                this.baseMapper.insertBDetail(activityDetail);
//            }
        } else {
            // 其他活动
            ActivityGpa activityGpa = BeanUtil.copyProperties(activityVo, ActivityGpa.class);
            activityGpa.setId(activityEntity.getContestNo());

            this.baseMapper.insertGpa(activityGpa);
        }

        // 删除活动缓存
        redisTemplate.delete("activityList");
    }

    @Override
    public Page managePage(Long currPage, Long pageSize, Long categoryId) {
        // 创建分页对象
        Page<ActivityEntity> page = new Page<>(currPage, pageSize);
        LambdaQueryWrapper<ActivityEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(categoryId)){
            queryWrapper.eq(ActivityEntity::getCategoryId, categoryId);
        }
        Page<ActivityEntity> activityEntityPage = this.baseMapper.selectPage(page,
                queryWrapper);
        return activityEntityPage;
    }

    @Override
    public Page examinePage(Long currPage, Long pageSize, Integer examineStatus) {
        Page<ActivityExamineEntity> page = new Page<>(currPage, pageSize);
        LambdaQueryWrapper<ActivityExamineEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(examineStatus)){
            queryWrapper.eq(ActivityExamineEntity::getExamineStatus, examineStatus);
        }

        Page<ActivityExamineEntity> activityEntityPage = activityExamineMapper.selectPage(page,
                queryWrapper);
        return activityEntityPage;
    }

    @Override
    public List<ActivityDetailResp> getActivityDetail(Long activityId) {
        ActivityEntity activityEntity = this.baseMapper.selectById(activityId);
        if (activityEntity.getCategoryId().equals(2L)){
            // 比赛
            if (activityEntity.getCategory().equals("A")) {
                return BeanUtil.copyToList(this.baseMapper.selectAList(), ActivityDetailResp.class);
            } else {
                return BeanUtil.copyToList(this.baseMapper.selectBList(), ActivityDetailResp.class);
            }
        } else {
            // 其他活动
            return this.baseMapper.selectGpaDetail(activityId);
        }
    }

    @Override
    public void updateDetail(ActivityDetailUpdate activityDetailUpdate) {
        ActivityEntity activityEntity = this.baseMapper.selectById(activityDetailUpdate.getActivityId());
        if (activityEntity.getCategoryId().equals(2L)) {
            // 比赛
            if (activityEntity.getCategory().equals("A")) {
                this.baseMapper.updateADetail(activityDetailUpdate.getGpa(),
                        activityDetailUpdate.getGrade(),
                        activityDetailUpdate.getLevel());
            } else {
                this.baseMapper.updateBDetail(activityDetailUpdate.getGpa(),
                        activityDetailUpdate.getGrade(),
                        activityDetailUpdate.getLevel());
            }
        } else {
            // 其他加分项
            this.baseMapper.updateDetail(activityDetailUpdate.getGpa(),
                    activityDetailUpdate.getSameTypeAdd(),
                    activityDetailUpdate.getType(),
                    activityDetailUpdate.getActivityId());

        }
    }
}
